import { ref, onMounted, computed } from 'vue';
import { cloneDeep } from 'lodash'
import { defineStore } from 'pinia';
import { useRouter } from 'vue-router'

import {
  getIpData,
  getweatherData,
  getadcodeData,
  getnowadcodeData,
  getnowweatherData,
} from '@/api/index.js';

export const useCodeStore = defineStore('code', () => {
  const router = useRouter()
  const mykey = ref('69912ba4b550aebc27a8026aaba4b9ee');
  const ip = ref('');
  const IpCity = ref('');
  const IpCityad = ref('');
  const weatherbase = ref({});
  const weatherall = ref({});
  // 城市名称
  const cityName = ref('');
  const nowWeather = ref({});
  const nowadcode = ref('');
  const nowcity = ref('');
  const nowWeatherall = ref({});


const citys=ref([])

// 持久化存储键名
  const STORAGE_KEY = 'weather-app-cities';


  onMounted(async () => {

     loadFromLocalStorage();

    // 获取IP地址
    const res = await getIpData();
    IpCity.value = res.city;
    // 获取城市编码
    const adcodeRes = await getadcodeData();
    if (
      adcodeRes &&
      adcodeRes.geocodes &&
      Array.isArray(adcodeRes.geocodes) &&
      adcodeRes.geocodes.length > 0
    ) {
      IpCityad.value = adcodeRes.geocodes[0].adcode;
      // 获取当日天气数据
      const baseWeatherRes = await getweatherData('base');
      weatherbase.value = baseWeatherRes;
      // 获取未来三天天气数据
      const allWeatherRes = await getweatherData('all');
      weatherall.value = allWeatherRes;
    }
  });

   // 从本地存储加载数据
  const loadFromLocalStorage = () => {
    try {
      const storedCitys = localStorage.getItem(STORAGE_KEY);
      if (storedCitys) {
        citys.value = JSON.parse(storedCitys);
      }
    } catch (error) {
      console.error('加载本地存储数据失败:', error);
      citys.value = [];
    }
  };

  // 保存数据到本地存储
  const saveToLocalStorage = () => {
    try{
      localStorage.setItem(STORAGE_KEY, JSON.stringify(citys.value));
    }catch(error){
      console.error('保存本地存储数据失败:', error);
    }
      
    
  };

  // 根据用户输入的城市获取天气数据
  const fetchWeatherByCity = async (city) => {
    if (!city) return;

    // 临时设置IpCity为用户输入的城市，以便获取adcode
    nowcity.value = city;

    
      // 获取adcode
      const adcodeRes = await getnowadcodeData();
      if (adcodeRes && adcodeRes.geocodes && adcodeRes.geocodes.length > 0) {
        nowadcode.value = adcodeRes.geocodes[0].adcode;
        

        // 获取基础天气数据
        const baseWeatherRes = await getnowweatherData('base');
        nowWeather.value = baseWeatherRes;

        // 获取详细天气数据
        const allWeatherRes = await getnowweatherData('all');
        nowWeatherall.value = allWeatherRes;

        return {
          success: true,
          data: { base: nowWeather.value, all: nowWeatherall.value },
        };
      } 
    
 };


 const currentWeather = computed(() => {
  return nowWeather.value.lives?.[0] || {}
})
const currentCity = computed(() => {
  return currentWeather.value.city || ''
})


// 添加城市并保存到本地存储
  const handleadd = () => {
    cityName.value = currentCity.value;
    if (cityName.value) {
      // 使用深拷贝创建独立对象
      const cityToAdd = cloneDeep({
        name: cityName.value,
        weather: currentWeather.value.temperature,
        adcode: nowadcode.value,
        timestamp: new Date().getTime(),
      });
      
      // 检查是否已存在相同城市
      const existingIndex = citys.value.findIndex(c => c.name === cityToAdd.name);
      if (existingIndex > -1) {
        // 更新已存在的城市
        citys.value.splice(existingIndex, 1, cityToAdd);
      } else {
        // 添加新城市
        citys.value.push(cityToAdd);
      }
      
      // 保存到本地存储
      saveToLocalStorage();
    }
    
    router.push('/');
    cityName.value = '';
  };

  // 删除城市并更新本地存储
  const handledelete = (index) => {
    citys.value.splice(index, 1);
    saveToLocalStorage();
  };

  return {
    mykey,
    ip,
    IpCity,
    IpCityad,
    weatherbase,
    weatherall,
    cityName,
    nowWeather,
    nowadcode,
    nowcity,
    nowWeatherall,
    fetchWeatherByCity,
handleadd,
currentCity,citys,handledelete

  };
});
